package com.zcxy360.sandtable.service;

import java.util.Arrays;
import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.zcxy360.sandtable.domain.DrawingSchedule;
import com.zcxy360.sandtable.domain.DrawingScheduleMapper;
import com.zcxy360.sandtable.domain.PlanSchedule;
import com.zcxy360.sandtable.domain.PlanScheduleMapper;
import com.zcxy360.sandtable.domain.StudentUnit;
import com.zcxy360.sandtable.domain.StudentUnitMapper;
import com.zcxy360.sandtable.domain.UnitProblem;
import com.zcxy360.sandtable.domain.UnitProblemMapper;
import com.zcxy360.sandtable.domain.User;
import com.zcxy360.sandtable.domain.VideoSchedule;
import com.zcxy360.sandtable.domain.VideoScheduleMapper;
import com.zcxy360.sandtable.domain.Vproblem;
import com.zcxy360.sandtable.domain.VproblemMapper;
import com.zcxy360.sandtable.util.ShiroUtil;

@Transactional
@Service
public class StudentUnitService {

	@Autowired
	private ObjectMapper objectMapper;
	@Autowired
	private StudentUnitMapper studentUnitMapper;
	@Autowired
	private UnitProblemMapper unitProblemMapper;
	@Autowired
	private VproblemMapper vproblemMapper;
	@Autowired
	private PlanScheduleMapper planScheduleMapper;
	@Autowired
	private VideoScheduleMapper videoScheduleMapper;
	@Autowired
	private DrawingScheduleMapper drawingScheduleMapper;

	public Object list(StudentUnit studentUnit, String orderByClause, Integer pageNum, Integer pageSize, Integer navigatePages) {
		User loginUser = ShiroUtil.getUser();
		String loginRole = loginUser.getRole();
		if(loginRole.equals("student")) {
			studentUnit.setUserId(loginUser.getUserId());
		}
		PageHelper.startPage(pageNum,pageSize);
		List<StudentUnit> studentUnits = studentUnitMapper.list(studentUnit,orderByClause);
		return new PageInfo<>(studentUnits, navigatePages);
	}
	
	public Object listWithStageUnitCascade(StudentUnit studentUnit, String orderByClause, Integer pageNum,
			Integer pageSize, Integer navigatePages) {
		User loginUser = ShiroUtil.getUser();
		if(loginUser.getRole().equals("student")) {
			studentUnit.setUserId(loginUser.getUserId());
		}
		PageHelper.startPage(pageNum,pageSize);
		List<StudentUnit> studentUnits = studentUnitMapper.listWithStageUnitCascade(studentUnit,orderByClause);
		return new PageInfo<>(studentUnits, navigatePages);
	}
	
	public Object listWithCascade(StudentUnit studentUnit, String orderByClause, Integer pageNum,
			Integer pageSize, Integer navigatePages) {
		User loginUser = ShiroUtil.getUser();
		if(loginUser.getRole().equals("student")) {
			studentUnit.setUserId(loginUser.getUserId());
		}
		PageHelper.startPage(pageNum,pageSize);
		List<StudentUnit> studentUnits = studentUnitMapper.listWithCascade(studentUnit,orderByClause);
		return new PageInfo<>(studentUnits, navigatePages);
	}
	
	public boolean update(StudentUnit studentUnit) {
		studentUnitMapper.updateByPrimaryKeySelective(studentUnit);
		return true;
	}

	public boolean submit(String answerJson) {
		Integer courseId = null;
		Integer unitId = null;
		Integer userId = ShiroUtil.getUser().getUserId();
		JavaType javaType = objectMapper.getTypeFactory().constructParametricType(List.class, UnitProblem.class);
		List<UnitProblem> unitProblems = null;
		try {
			unitProblems = objectMapper.readValue(answerJson, javaType);
			courseId = unitProblems.get(0).getCourseId();
			unitId = unitProblems.get(0).getUnitId();
		} catch (Exception e) {
			e.printStackTrace();
			throw new RuntimeException("解析数据失败");
		} 
		Vproblem vProblem;
		boolean isAllSubject = true;
		int score;
		int totalScore = 0;
		int rigthScore = 0;
		String correctAnswer;
		String answer;
		List<String> correctAnswerList;
		List<String> answerList;
		for(UnitProblem unitProblem:unitProblems) {
			unitProblem.setUserId(userId);
			vProblem = vproblemMapper.selectByPrimaryKey(unitProblem.getVproblemId());
			score = vProblem.getScore();
			totalScore += score;
			correctAnswer = vProblem.getCorrectAnswer();
			answer = unitProblem.getAnswer();
			if(answer.startsWith(",")) {
				answer = answer.substring(1);
				unitProblem.setAnswer(answer);
			}
			if(vProblem.getType() == 1) {
				isAllSubject = false;
			}else {
				correctAnswerList = Arrays.asList(correctAnswer.split(","));
				answerList = Arrays.asList(answer.split(","));
				if(correctAnswerList.size() == answerList.size() && answerList.containsAll(correctAnswerList)) {
					rigthScore += score;
					unitProblem.setProblemScore(score);
				}
			}
		}
		for(UnitProblem unitProblem:unitProblems) {
			unitProblemMapper.updateByPrimaryKeySelective(unitProblem);
		}
		
		StudentUnit studentUnit = new StudentUnit();
		studentUnit.setCourseId(courseId);
		studentUnit.setUnitId(unitId);
		studentUnit.setUserId(userId);
		studentUnit.setUnitScore(isAllSubject?rigthScore*100/totalScore:0);
		studentUnit.setIsPublished(isAllSubject?true:false);
		studentUnitMapper.submit(studentUnit);
		return true;
	}
	
	public boolean mark(String markJson) {
		JavaType javaType = objectMapper.getTypeFactory().constructParametricType(List.class, UnitProblem.class);
		List<UnitProblem> unitProblems = null;
		try {
			unitProblems = objectMapper.readValue(markJson, javaType);
		} catch (Exception e) {
			e.printStackTrace();
			throw new RuntimeException("解析数据失败");
		} 
		for(UnitProblem unitProblem:unitProblems) {
			unitProblemMapper.updateByPrimaryKeySelective(unitProblem);
		}
		UnitProblem unitProblem = unitProblems.get(0);
		StudentUnit studentUnit = new StudentUnit();
		studentUnit.setCourseId(unitProblem.getCourseId());
		studentUnit.setUserId(unitProblem.getUserId());
		studentUnit.setUnitId(unitProblem.getUnitId());
		studentUnit.setIsPublished(true);
		studentUnit.setPublishTime(new Date());
		studentUnitMapper.updateByPrimaryKeySelective(studentUnit);
		return true;
	}

	public boolean usePlan(PlanSchedule planSchedule) {
		planSchedule.setUserId(ShiroUtil.getUser().getUserId());
		planSchedule.setIsUsed(true);
		planScheduleMapper.updateByPrimaryKeySelective(planSchedule);
		return true;
	}

	public boolean useVideo(VideoSchedule videoSchedule) {
		videoSchedule.setUserId(ShiroUtil.getUser().getUserId());
		videoSchedule.setIsUsed(true);
		videoScheduleMapper.updateByPrimaryKeySelective(videoSchedule);
		return true;
	}

	public boolean useDrawing(DrawingSchedule drawingSchedule) {
		drawingSchedule.setUserId(ShiroUtil.getUser().getUserId());
		drawingSchedule.setIsUsed(true);
		drawingScheduleMapper.updateByPrimaryKeySelective(drawingSchedule);
		return true;
	}

	public boolean back(Integer courseId,Integer userId,Integer unitId) {
		StudentUnit studentUnit = studentUnitMapper.selectByPrimaryKey(courseId,userId, unitId);
		if(studentUnit != null) {
			studentUnit.setIsCommitted(false);
			studentUnit.setCompletion(studentUnit.getCompletion()-studentUnit.getScale());
			studentUnitMapper.updateByPrimaryKeySelective(studentUnit);
		}
		return true;
	}




}
